#include "Sound.h"

Sound::Sound(string *fileList, int nb, int ch) {

	FMOD_System_Create(&system);
	FMOD_System_Init(system, ch, FMOD_INIT_NORMAL, NULL);
	pos = 0;
	this->channel = ch;

	float volume;
	FMOD_CHANNELGROUP *canal;


	for ( int i = 0 ; i < nb ; i++ ) {

		FMOD_SOUND * temp;
		string tempFile = "Sounds/" + fileList[i] + ".ogg";
		res = FMOD_System_CreateSound(system, tempFile.c_str(), FMOD_CREATESAMPLE, 0, &temp);

		if (res != FMOD_OK) {
			cout << "Impossible de charger " << tempFile << endl;
			exit(EXIT_FAILURE);
		}

		sounds.push_back(temp);

	}

	FMOD_System_GetMasterChannelGroup(system, &canal);
	FMOD_ChannelGroup_GetVolume(canal, &volume);
	FMOD_ChannelGroup_SetVolume(canal, volume / 10);

}

Sound::Sound(int ch) {
	FMOD_System_Create(&system);
	FMOD_System_Init(system, ch, FMOD_INIT_NORMAL, NULL);
	pos = 0;
	this->channel = ch;
}

void Sound::addSound(string sound) {
	FMOD_SOUND * temp;
	string tempFile = "Sounds/" + sound + ".ogg";
	res = FMOD_System_CreateSound(system, tempFile.c_str(), FMOD_CREATESAMPLE, 0, &temp);

	if (res != FMOD_OK) {
		cout << "Impossible de charger " << tempFile << endl;
		exit(EXIT_FAILURE);
	}

	sounds.push_back(temp);
}

void Sound::randPlay() {
	int size = sounds.size();
	int play;

	srand (time(NULL));
	play = rand() % size;
	FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sounds[play], 0, NULL);
}

void Sound::playNext() {
	if ( pos  == sounds.size() - 1 )
		pos = 0;
	else
		pos++;
	FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sounds[pos], 0, NULL);
}

void Sound::playPrev() {
	if ( pos  == 0 )
		pos = sounds.size() - 1;
	else
		pos--;
	FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sounds[pos], 0, NULL);
}

void Sound::playCurrent() {
	FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sounds[pos], 0, NULL);
}

void Sound::play(int sound) {
	if ( ! (sound < 0 || sound > sounds.size() - 1) ) {
		pos = sound;
		FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sounds[pos], 0, NULL);
	} else {
		randPlay();
	}
}
